package com.pengshun.modules.api.user.service.impl;

import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.coal.service.dto.MerchantDto;
import com.pengshun.modules.api.coal.service.mapstruct.MerchantMapper;
import com.pengshun.modules.api.mapper.SystemMapper;
import com.pengshun.modules.api.system.service.dto.AddresDto;
import com.pengshun.modules.api.user.para.UserPara;
import com.pengshun.modules.common.*;
import com.pengshun.modules.api.coal.repository.UserRepository;
import com.pengshun.modules.api.user.repository.CarOwnerRepository;
import com.pengshun.modules.api.user.repository.CitizenRepository;
import com.pengshun.modules.api.user.repository.DrivingLicenseRepository;
import com.pengshun.modules.api.user.service.AuthenticationService;
import com.pengshun.modules.api.user.service.dto.CitizenDto;
import com.pengshun.modules.api.user.service.dto.DrivingLicenseDto;
import com.pengshun.modules.api.user.service.mapstruct.CitizenTodo;
import com.pengshun.modules.api.user.service.mapstruct.DrivingLicenseTodo;
import com.pengshun.modules.domain.Citizen;
import com.pengshun.modules.domain.DrivingLicense;
import com.pengshun.modules.domain.Merchant;
import com.pengshun.modules.domain.User;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Locale;

@Service
@RequiredArgsConstructor
public class AuthenticationServiceImpl implements AuthenticationService {


    private final CitizenRepository citizenRepository;

    private final CitizenTodo citizenTodo;

    private final DrivingLicenseRepository drivingLicenseRepository;

    private final DrivingLicenseTodo drivingLicenseTodo;

    private final CarOwnerRepository carOwnerRepository;

    private final SystemMapper systemMapper;

    private final UserRepository userRepository;

    private final MerchantRepository merchantRepository;

    private final MerchantMapper merchantMapper;

    private  final MessageSource messageSource;

    @Override
    public BaseResult idcard(CitizenDto para) {
        String cc = IDCardUtil.IDCardValidate(para.getIdCardNum());
        if (!"YES".equals(cc)) {
            return new BaseResult(1, cc);
        }
        Citizen citizens = citizenRepository.findByUserId(para.getUserId());
        if (citizens != null) {
            if (citizens.getReviewStatus().longValue() == AuthenticationStatus.ONE_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.idcard.getReviewStatus", null, Locale.CHINA));
            }
            if (citizens.getReviewStatus().longValue() == AuthenticationStatus.TWO_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.idcard.longValue", null, Locale.CHINA));
            }
        }

        if (para.getId() != null) {
            Citizen citizen = citizenRepository.findById(para.getId()).orElseGet(Citizen::new);
            citizen.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            citizen.setName(para.getName());
            citizen.setIdCardNum(para.getIdCardNum());
            citizen.setApplyDate(new Date());
            citizen.setIdCardFrontImg(para.getIdCardFrontImg());
            citizen.setIdCardBackImg(para.getIdCardBackImg());
            citizenRepository.save(citizen);
        } else {
            para.setApplyDate(new Date());
            para.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            para.setType(UserType.ZERO_STATUS);
            citizenRepository.save(citizenTodo.toEntity(para));
        }
        //更改用户状态
        User user =userRepository.findById(para.getUserId()).orElseGet(User::new);
        user.setStatus(AuthenticationStatus.ONE_STATUS);
        userRepository.save(user);
        return new BaseResult(0,messageSource.getMessage("save.success", null, Locale.CHINA));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult driver(DrivingLicenseDto para, CitizenDto dto) throws Exception {
        String cc = IDCardUtil.IDCardValidate(para.getIdcard());
        if (!"YES".equals(cc)) {
            return new BaseResult(1, cc);
        }
        DrivingLicense license = drivingLicenseRepository.findByUserId(para.getUserId());
        if (license != null) {
            if (license.getStatus().longValue() == AuthenticationStatus.ONE_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.driver", null, Locale.CHINA));
            }
            if (license.getStatus().longValue() == AuthenticationStatus.TWO_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.longValue", null, Locale.CHINA));
            }
        }
        Citizen citizen = null;
        para.setDrivingStatus(1);
        if (para.getDrivingLicenseId() != null) {
            citizen = citizenRepository.findByUserId(para.getUserId());
            //说明是重新提交资料
            citizen.setName(para.getName());
            citizen.setIdCardNum(para.getIdcard());
            citizen.setApplyDate(new Date());
            citizen.setType(UserType.ONE_STATUS);
            citizen.setIdCardBackImg(dto.getIdCardBackImg());
            citizen.setIdCardFrontImg(dto.getIdCardFrontImg());
            citizen.setReviewStatus(AuthenticationStatus.ONE_STATUS);

            license.setStatus(AuthenticationStatus.ONE_STATUS);
            license.setName(para.getName());
            license.setIdcard(para.getIdcard());
            license.setDlImageFront(para.getDlImageFront());
            license.setDlImageBack(para.getDlImageBack());

        } else {
            dto.setUserId(para.getUserId());
            dto.setIdCardNum(para.getIdcard());
            dto.setIdCardFrontImg(dto.getIdCardFrontImg());
            dto.setType(UserType.ONE_STATUS);
            dto.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            dto.setApplyDate(new Date());
            citizen = citizenTodo.toEntity(dto);
            para.setStatus(AuthenticationStatus.ONE_STATUS);
            para.setCreatTime(new Date());
            license=drivingLicenseTodo.toEntity(para);
        }
        //实名人认证表添加记录
        citizenRepository.save(citizen);
        //更改用户状态
        User user =userRepository.findById(para.getUserId()).orElseGet(User::new);
        user.setStatus(AuthenticationStatus.ONE_STATUS);
        userRepository.save(user);
        //司机认证表添加记录

        drivingLicenseRepository.save(license);
        return new BaseResult(0,messageSource.getMessage("save.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult carowner(CitizenDto para) throws Exception {
        String cc = IDCardUtil.IDCardValidate(para.getIdCardNum());
        if (!"YES".equals(cc)) {
            return new BaseResult(1, cc);
        }
        Citizen citizens = citizenRepository.findByUserId(para.getUserId());
        if (citizens != null) {
            if (citizens.getReviewStatus().longValue() == AuthenticationStatus.TWO_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.driver", null, Locale.CHINA));
            }
            if (citizens.getReviewStatus().longValue() == AuthenticationStatus.ONE_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.longValue", null, Locale.CHINA));
            }
        }
        if (para.getId() != null) {
            Citizen citizen = citizenRepository.findById(para.getId()).orElseGet(Citizen::new);
            citizen.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            citizen.setName(para.getName());
            citizen.setIdCardNum(para.getIdCardNum());
            citizen.setIdCardFrontImg(para.getIdCardFrontImg());
            citizen.setIdCardBackImg(para.getIdCardBackImg());
            citizen.setApplyDate(new Date());
            citizen.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            citizenRepository.save(citizen);
        } else {
            para.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            para.setApplyDate(new Date());
            para.setType(UserType.ZERO_STATUS);
            para.setType(UserType.TWO_STATUS);
            citizenRepository.save(citizenTodo.toEntity(para));
        }
        User user = userRepository.findById(para.getUserId()).orElseGet(User::new);
        user.setStatus(AuthenticationStatus.ONE_STATUS);
        userRepository.save(user);
        return new BaseResult(0,messageSource.getMessage("save.success", null, Locale.CHINA));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult merchant(MerchantDto para, CitizenDto paras) throws Exception {
        String cc = IDCardUtil.IDCardValidate(para.getIdCardNum());
        if (!"YES".equals(cc)) {
            return new BaseResult(1, cc);
        }
        Merchant merchant = merchantRepository.findByUserId(para.getUserId());
        if (merchant != null) {
            if (merchant.getReviewStatus().longValue() == AuthenticationStatus.ONE_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.driver", null, Locale.CHINA));
            }
            if (merchant.getReviewStatus().longValue() == AuthenticationStatus.TWO_STATUS) {
                return new BaseResult(1, messageSource.getMessage("AuthenticationServiceImpl.driver.longValue", null, Locale.CHINA));
            }
        }


        if (para.getId() != null) {
            Citizen citizen = citizenRepository.findByUserId(para.getUserId());
            if (para.getIsLegalPerson() == 0) {

                merchant.setIdCardBackImg(para.getIdCardBackImg());
                merchant.setIdCardFrontImg(para.getIdCardFrontImg());
                merchant.setIdCardBackImgs(para.getIdCardBackImgs());
                merchant.setIdCardFrontImgs(para.getIdCardFrontImgs());
                //不是法人
                merchant.setBookPic(para.getBookPic());
            }else{

                merchant.setIdCardBackImg(para.getIdCardBackImgs());
                merchant.setIdCardFrontImg(para.getIdCardFrontImgs());

                merchant.setIdCardBackImgs(null);
                merchant.setIdCardFrontImgs(null);
            }
            citizen.setIdCardFrontImg(merchant.getIdCardFrontImg());
            citizen.setIdCardBackImg(merchant.getIdCardBackImg());
            citizen.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            citizen.setName(para.getName());
            citizen.setApplyDate(new Date());
            citizen.setIdCardNum(para.getIdCardNum());
            citizenRepository.save(citizen);

            merchant.setReviewStatus(AuthenticationStatus.ONE_STATUS);
            AddresDto city = systemMapper.selectBysdId(para.getAdcode());
            merchant.setSpId(city.getProvinceId());
            merchant.setScId(city.getCityId());
            merchant.setAdcode(para.getAdcode() + "");
            merchant.setIsLegalPerson(para.getIsLegalPerson());
            if (para.getWayPic() != null) {
                merchant.setWayPic(para.getWayPic());
            }

            merchant.setName(para.getName());
            merchant.setIdCardName(para.getIdCardName());
            merchant.setIdCardNum(para.getIdCardNum());
            merchant.setLngX(para.getLongitude()!=null?para.getLongitude():merchant.getLngX());
            merchant.setLatY(para.getLatitude()!=null?para.getLatitude():merchant.getLatY());
            merchant.setProvince(para.getProvince());
            merchant.setCity(para.getCity());
            merchant.setDistrict(para.getDistrict());
            merchant.setDetailAddress(para.getDetailAddress());
            merchant.setBusinessLicenseImg(para.getBusinessLicenseImg());
            merchant.setDoorImg(para.getDoorImg());
            merchant.setLinkman(para.getLinkman());
            merchant.setLinkmanPhone(para.getLinkmanPhone());
            merchant.setLookNum(Math.round((Math.random()+1) * 1000));
            merchant.setDataStatus(1);
            merchantRepository.save(merchant);
        } else {
            AddresDto city = systemMapper.selectBysdId(para.getAdcode());
            para.setSpId(city.getProvinceId());
            para.setScId(city.getCityId());
            para.setApplyDate(new Date());
            para.setLevel(2);
            para.setLngX(para.getLongitude());
            para.setLatY(para.getLatitude());
            para.setBusinessType(2);
            para.setScore(new BigDecimal(5.0));
            para.setStatus(AuthenticationStatus.ONE_STATUS);
            para.setReviewStatus(AuthenticationStatus.ONE_STATUS);

            para.setSource(0);
            if (para.getIsLegalPerson() ==1) {
                para.setIdCardBackImg(para.getIdCardBackImgs());
                para.setIdCardFrontImg(para.getIdCardFrontImgs());
                para.setIdCardBackImgs(null);
                para.setIdCardFrontImgs(null);
            }
            //实名信息
            paras.setIdCardBackImg(para.getIdCardBackImg());
            paras.setIdCardFrontImg(para.getIdCardFrontImg());
            paras.setApplyDate(new Date());
            paras.setUserId(para.getUserId());
            paras.setType(3);
            paras.setReviewStatus(AuthenticationStatus.ONE_STATUS);

            citizenRepository.save(citizenTodo.toEntity(paras));
            Merchant merchant1=merchantMapper.toEntity(para);
            merchant1.setLookNum(Math.round((Math.random()+1) * 1000));
            merchantRepository.save(merchant1);
        }
        User user = userRepository.findById(para.getUserId()).orElseGet(User::new);
        user.setStatus(AuthenticationStatus.ONE_STATUS);
        userRepository.save(user);
        return new BaseResult(0,messageSource.getMessage("save.success", null, Locale.CHINA));

        //todo 审核通过 更新实名状态为通过  用户表更新姓名
    }

    @Override
    public BaseResult getAutentication(UserPara para) {
        //:普通用户,1司机,2车主,3运输公司,4煤炭商,
        if (para.getUserType() == 0 || para.getUserType() == 2) {
            Citizen citizen = citizenRepository.findByUserId(para.getId());
            return new BaseResult(0, citizen);
        } else if (para.getUserType() == 1) {
            DrivingLicense license = drivingLicenseRepository.findByUserId(para.getId());
            Citizen citizen = citizenRepository.findByUserId(para.getId());
            DrivingLicenseDto drivingLicenseDto=drivingLicenseTodo.toDto(license);
            drivingLicenseDto.setIdCardFrontImg(citizen.getIdCardFrontImg());
            drivingLicenseDto.setIdCardBackImg(citizen.getIdCardBackImg());
            return new BaseResult(0, drivingLicenseDto);
        } else {
            MerchantDto merchant = merchantMapper.toDto(merchantRepository.findByUserId(para.getId()));
//            if (merchant.getIsLegalPerson() == 1) {
//                merchant.setIdCardBackImgs(merchant.getIdCardBackImg());
//                merchant.setIdCardFrontImgs(merchant.getIdCardFrontImg());
//                merchant.setIdCardBackImg(null);
//                merchant.setIdCardFrontImg(null);
//            } else {
//                Citizen citizen = citizenRepository.findByUserId(para.getId());
//                merchant.setIdCardName(citizen.getName());
//                merchant.setIdCardNum(citizen.getIdCardNum());
//                merchant.setIdCardBackImgs(merchant.getIdCardBackImg());
//                merchant.setIdCardFrontImgs(merchant.getIdCardFrontImg());
//                merchant.setIdCardBackImg(citizen.getIdCardBackImg());
//                merchant.setIdCardFrontImg(citizen.getIdCardFrontImg());
//            }
            return new BaseResult(0, merchant);
        }
    }
}
